package Ske

import (
	"github.com/PuerkitoBio/goquery"
	"log"
	"io"
	"fmt"
	"time"
	"strings"
	"github.com/trysh/ttb"
	"os"
	"github.com/gin-gonic/gin/json"
	json2 "encoding/json"
	"regexp"
	"errors"
	"net/smtp"
	"bytes"
	"bufio"
	"io/ioutil"
	"html/template"
)

const  PATH_STATIC  =  "tmpl/ "

type JStroe map[string] map[string]interface{}
var gJobdes JStroe
var gFileStore *os.File

var gNewJob map[string] interface{}


func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsExist(err) {
		return true, nil
	}
	return false, err
}

func GetTemplateFile(template string) ([]byte,error){
	path := "tmpl//" +template+".html"
	ok,err := PathExists(path)
	if !ok{
		return nil,errors.New("Count not Find File " + path)
	}
	file,err := os.Open(path)
	if err != nil{
		log.Println(err.Error())
	}
	ret,err := ioutil.ReadAll(file)
	file.Close()
	return ret,nil
}
/**     
  * @function SendToMail
  * @Description: 发送邮件
  * @Author:         Administrator
  * @CreateDate:     2018/2/25 0025 下午 10:59
  * @UpdateUser: Administrator
  * @UpdateDate: 2018/2/25 0025 下午 10:59
  * @inpara:
  
  *@outpara:
    
  
  */
func SendToMail(title,user, password, host, to,tplname string, content interface{}, mailtype string,ifgenerate bool) error {
	var content_type string
	var paseresult bytes.Buffer
	writer := bufio.NewWriter(&paseresult)
	hp := strings.Split(host, ":")
	auth := smtp.PlainAuth("", user, password, hp[0])

	if mailtype == "html" {
		content_type = "Content-Type: text/" + mailtype + "; charset=UTF-8"
	} else {
		content_type = "Content-Type: text/plain" + "; charset=UTF-8"
	}

	//todo 获取模板文件内容
	tpl,err := GetTemplateFile(tplname)
	if err !=nil{
		log.Println(err.Error())
		return err
	}
	//todo 渲染
	tparse := template.New(tplname)
	tparse, err = tparse.Parse(string(tpl))
	if err !=nil{
		log.Println(err.Error())
		return  err
	}
	err = tparse.Execute(writer,content)
	if err !=nil{
		log.Println(err.Error())
		return  err
	}
	writer.Flush()

	//log.Println(string(tpl))
	log.Println(string(paseresult.String()))

	if err != nil{
		log.Println(err.Error())
		return err
	}

	msg := []byte("To: " + to + "\r\nFrom: " + user + "\r\nSubject: " + title + "\r\n" +
		content_type  + "\r\n\r\n"+ paseresult.String() + "\r\n" )
	send_to := strings.Split(to, ";")

	//todo 如果生成Html文件
	if ifgenerate{
		file,err := os.Create(PATH_STATIC + tplname + ".html")
		if err != nil{
			log.Println(err.Error())
		}
		file.WriteString(paseresult.String())
		file.Close()
	}
	//检测是否是邮件地址
	for k,_ := range send_to{
		match, _ := regexp.MatchString("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?", send_to[k])
		if !match{
			return errors.New("Format Error")
		}
	}

	err = smtp.SendMail(host, auth, user,send_to, msg)
	if err !=nil{
		return err
	}
	return err
}
/**     
  * @function init
  * @Description:     模块初始化
  * @Author:         Administrator
  * @CreateDate:     2018/2/25 0025 上午 12:12
  * @UpdateUser: Administrator
  * @UpdateDate: 2018/2/25 0025 上午 12:12
  * @inpara:
  
  *@outpara:
    
  
  */
func init() {
	var e error
	gJobdes = make(JStroe)
	gNewJob = make(map[string]interface{},1)

	gNewJob["job"] = []map[string]string{}
	gFileStore,e = os.OpenFile("job.data",os.O_RDWR,666)
	if e !=nil{
		log.Println(e.Error(),"\r\nnow create it\r\n")
		gFileStore,e = os.Create("job.data")
	}
	inf,_ := gFileStore.Stat()
	b1 := make([]byte, inf.Size())
	gFileStore.Read(b1)
	//fmt.Printf("%d bytes: %s\n", n1, string(b1))
	json2.Unmarshal(b1,&gJobdes)
	if e!=nil{
		log.Println("error init file\r\n")
	}
	//log.Println(gJobdes)

}
/**     
  * @function CaptrueIntereJob
  * @Description:  爬职位数据存在gJobdes 全局变量中s
  * @Author:
  * @CreateDate:     2018/2/24 0024 下午 10:43
  * @UpdateUser: 
  * @UpdateDate: 2018/2/24 0024 下午 10:43
*/
func CaptrueIntereJob(jNmae string,w io.Writer) {
	searchtpl := "https://www.xmrc.com.cn/net/info/resultg.aspx?a=a&g=g&jobtype=&releaseTime=365&searchtype=1"
	keyword := "&keyword=" + jNmae + "&sortby=updatetime&ascdesc=Desc"

	//@ 最大100页数据
	for i :=1;i<100;i++{
		page := "&PageIndex=" + ttb.Itoa(i)
		url := searchtpl + keyword + page
		doc, err := goquery.NewDocument(url)
		if err != nil {
			log.Fatal(err)
		}
		if(url != doc.Url.String()){
			break;
		}

		doc.Find(".queryRecruitTable").Find("tr").Each(func(i int, s *goquery.Selection) {
			tmp := map[string] string{}
			s.Find("td").Each(func(i int, s1 *goquery.Selection) {
				v := s1.Find("a").Text()
				v = strings.TrimSpace(v)
				switch i {
				case 1:
					url,ok := s1.Find("a").Attr("href")
					if ok{
						tmp["url"] = "https://"+doc.Url.Host +"/net/info/"+ url
					}
					ID := strings.Split(url,"ID=")
					tmp["id"] = ID[1]
					tmp["name"] = v
					break
				case 2:
					tmp["cname"] = v
					break
				case 3:
					tmp["locate"] = v
					break
				case 4:
					tmp["salary"] = v
					break
				case 5:
					tmp["edu"] = v
					break
				case 7:
					v := s1.Find(".appjob").Text()
					v = strings.TrimSpace(v)
					tmp["time"] = v
					break
				}
			})
			if cpname,ok := tmp["cname"];ok{

				if _,ok := gJobdes[cpname];ok{
					gJobdes[cpname][tmp["id"]] = tmp
					gNewJob["job"] = append(gNewJob["job"].([]map[string]string),tmp)
				}else {
					ins := make(map[string]interface{},1)
					gJobdes[cpname] = ins
					gJobdes[cpname][tmp["id"]] = tmp
					// 新的职位发邮件通知
					gJobdes[cpname][tmp["id"]] = tmp
					gNewJob["job"] = append(gNewJob["job"].([]map[string]string),tmp)
				}
			}
		})
	}
	gNewJob["date"] = time.Now().Format("Mon Jan 2 15:04:05 -0700 MST 2006")
	SendToMail("新的订阅邮件通知",gGlobalConf.User,gGlobalConf.Password,gGlobalConf.Host,
		"421593804@qq.com","noticejob",gNewJob,"html",false)
}
/**     
  * @function MonitorJob
  * @Description:     每5秒钟监控map的数据
  * @Author:         Administrator
  * @CreateDate:     2018/2/24 0024 下午 10:44
  * @UpdateUser: Administrator
  * @UpdateDate: 2018/2/24 0024 下午 10:44
  * @inpara:
  *@outpara:
  */
func MonitorJob() {
	ok := true
	go func() {
		for ok{
			time.Sleep(5 * time.Second)
			for i,_ := range gJobdes{
				fmt.Println(i,gJobdes[i])
			}
			ok = false
		}
		c,e := json.Marshal(gJobdes)
		if e != nil{
			log.Println(e.Error())
		}
		inf,_ := gFileStore.Stat()
		gFileStore.Truncate(inf.Size())
		gFileStore.Sync()
		_,e = gFileStore.WriteAt(c,0)
		if e !=nil{
			gFileStore.Sync()
		}
	}()
}